﻿# -*- coding: utf-8 -*-

from mod_python import apache,psp,Cookie
import cPickle as p
import cgi
import cgitb
import sys
import os,shutil
import urllib2
import time
import Get_total,Add_total
import Sub_bala,Get_bala

# 定义系统根目录
root = 'D:\Program Files\Apache2.2\htdocs\py\Orderbook_2.0'

# 启用数据文件
userlistfile = root+'\data\userlist.data'
f = file(userlistfile)
userlist = p.load(f)        

# 登陆功能后台
def login(req,username,password):
    # 确保用户提供了所有的参数
    if not(username and password):
        return "No username or password, please enter again!"

    # 核对用户名和密码
    running = True 
    while running:
        account = username
        password = password

        #return account,password,userlist
        if account in userlist:
            if password==userlist[account][0]: 
                running=False
                #return "Login successfully!"
                #template=psp.PSP(req,filename=root+'\logon_OrderBook.html')
                #template.run()

                # 读取Cookie
                #if os.getenv('HTTP_COOKIE')!= None:
                #   cookie = Cookie.SimpleCookie(os.environ['HTTP_COOKIE'])
                #   return cookie
                cook = Cookie.get_cookies(req)
                if cook.has_key('account'):
                    return "yes"
                
                # 设置cookie                                
                #cookie = Cookie.Cookie('name',account)
                #Cookie.add_cookie(req,cookie)
                #cookie["name"] = account
                #cookie["name"]["expires"] = 100000
                #cookie["name"]["path"] = "/"
                #start_response("200 ok",[("content-Type","text/html; charset=UTF-8"),('Set-Cookie',cookie.output(header=""))])
                #return cookie

                # 返回主页
                logonfile = open(root+'\logon.htm','r')
                #logonfile = open(root+'\index.htm','r')
                skipfile = logonfile.read()
                dict={'name':userlist[account][1],
                      'account':account,
                      'ImageRoot':root+'\image',
                      'CssRoot':root+'\css'}
                return skipfile % dict
                #return "<h1>%s</h1><p>%s</p>\n" % (account, password)
                #req.write(Skipfile % dict[1])
                #return apache.OK
            else:
                return "Wrong password! Please try again.."
		#return "密码错误，请查证后重新登录"            
        else:
            #return "该用户不存在!"
 	    return "User not exists!"


# 注册功能后台
def register(req,textfield1,textfield2,textfield3,textfield4,textfield5):
    # 确保用户提供了所有的参数
    if not(textfield1 and textfield2 and textfield3 and textfield4 and textfield5):
        #return "您输入的注册信息不完整，请填写完整后注册！"
	return "Incomplete information! Please re-enter"

    running=True 
    while running:
        account = textfield1
        password = textfield2
        re_password = textfield3
        name = textfield4
        dorm = textfield5

        # 检查用户输入参数的正确性
        if account in userlist:
            #return userlist
            #return "该用户名已存在，请返回后重新输入!"
	    return "User exists!"
        elif password!=re_password:
            #return "您两次输入的密码不相符，请返回后重新输入!"
    	    return "Entered different passwords! Please re-enter"
    
        else:

            filename = account
            SDfile = root+'\data\\'+filename
            os.mkdir(SDfile)
            infofile = 'Per_info.data'
            Per_info = [account,name,dorm,0,0]
            f2 = file(infofile, 'w')
            p.dump(Per_info, f2) 
            f2.close()
            shutil.move('Per_info.data',SDfile)

            userlist[account]=[password,name,dorm]

            f = file(userlistfile, 'w')
            p.dump(userlist, f)
            running = False
            f.close()

            #req.write("注册成功!")            
            #Indexfile = open(root+'\index.htm','r')
            #skipindexfile = Indexfile.read()
            #dict={'ImageRoot':root+'\image',
            #      'CssRoot':root+'\css'}
            #return skipindexfile % dict
            #return "注册成功!请从网站首页登录···"
	    return "Register successfully!"


# 点单计算总价功能后台
def OrderMenu(req,account,name,select1,select2,select3,select4,select5,select6,select7,select8,select9,select10):

    # 赋值给list
    list=[account,select1,select2,select3,select4,select5,select6,select7,select8,select9,select10]
    #return list[1]

    os.chdir(root+"\data")

    shutil.copyfile("stylelist.data","stylelist2.data")

    def cal_(list):
        stylelistfile = "stylelist2.data"
        f = file(stylelistfile)
        stylelist = p.load(f)
    
        for i in range(1,len(list)):
            if list[i]!=0:
                price=stylelist[i-1]
                price[1]=list[i]
                
        f = file(stylelistfile, 'w')
        p.dump(stylelist, f) 
        f.close()

        stylelistfile = "stylelist2.data"
        f = file(stylelistfile)
        stylelist = p.load(f)
                
        Style_Num=''      
        for i in range(0,len(stylelist)):
            price=stylelist[i]
            if price[1]!= '0':
                Style_Num+=str(i)+str(price[1]) 
        
    
        sum=0
        for style,price in stylelist.items():
                sum+=int(price[0])*int(price[1])        
        return sum,Style_Num
    
    pay = cal_(list)
    os.remove('stylelist2.data')
    os.chdir(root)

    #return pay[0],pay[1]
    #MenuNum = len(pay[1])/2
    dialog='您的所点菜单如下：<br>'
    for i in range(0,len(pay[1]),2):
        dialog += '<br>'
        dialog += ' %s 号餐: %s 份' % (pay[1][i],pay[1][i+1])

    dialog +=  '<br><br>'+'需支付金额为: '+ str(pay[0])+' 元'

    #return dialog

    # 链接到确认支付页面
    Orfile = open(root+'\OrderMenu.html','r')
    skipOrfile = Orfile.read()
    bala=Get_bala.get_bala(account)
    #return skipOrfile
    dict={'dialog':dialog,
          'list0':list[0],
          'list1':list[1],
          'list2':list[2],
          'list3':list[3],
          'list4':list[4],
          'list5':list[5],
          'list6':list[6],
          'list7':list[7],
          'list8':list[8],
          'list9':list[9],
          'list10':list[10],
          'name':name,
          'balance':bala,
          'Root':root,
          'ImageRoot':root+'\image',
          'CssRoot':root+'\css'}

    return skipOrfile % dict


# 支付结算功能后台
def SettlePay(req,list0,list1,list2,list3,list4,list5,list6,list7,list8,list9,list10,RadioGroup1):

    list=[list0,list1,list2,list3,list4,list5,list6,list7,list8,list9,list10]
    RG=RadioGroup1

    if RG == '1':
        os.chdir(root+"\data")
        account=list[0]

        global Tm,Tm_d

        shutil.copyfile("stylelist.data","stylelist2.data")
        Tm=time.strftime('%Y-%m-%d %H%M%S',time.localtime(time.time()))
        Tm_ymd=time.strftime('%Y-%m-%d',time.localtime(time.time()))
        Tm_d=Tm+'.data'
        os.rename("stylelist2.data",Tm_d)

        def mov_():   
            
            Add_total.add_total(account)
            total=Get_total.get_total(account)
            Tm_d2=str(total)+Tm_d
            os.rename(Tm_d,Tm_d2)
            
            if int(Tm_d2[-7])!=0:
                Tm_d3=Tm_d2[:-7]+str(int(Tm_d2[-7:-5])+1)+account+'.data'
            else:
                Tm_d3=Tm_d2[:-6]+str(int(Tm_d2[-6])+1)+account+'.data'
            
            filename=list[0]
            if os.path.exists(filename):
                shutil.copyfile(Tm_d2,Tm_d3)
                shutil.move(Tm_d2,filename)
                shutil.move(Tm_d3,Tm_ymd)
            else:
                os.mkdir(filename)
                shutil.move(Tm_d2,filename)

        def cal_(list):
            stylelistfile=Tm_d
            f = file(stylelistfile)
            stylelist = p.load(f)
            #return stylelist
        
            for i in range(1,len(list)):
                if list[i]!='0':
                    stylelist[i-1][1]=int(list[i])
                          
            f = file(stylelistfile, 'w')
            p.dump(stylelist, f) 
            f.close()
            
            sum=0
            for style,price in stylelist.items():
                zl=int(price[0])*int(price[1])
                sum+=zl

            return sum
            
        sum=cal_(list)
        #return sum

        if sum!=0:
            mov_()
            return "Ordered successfully! We will send the order to you in half hours,please prapare money: %s yuan!" % sum
        else:
            os.remove(Tm_d)
            return "There is no order!Please go back to order something!"

    else:

        os.chdir(root+"\data")
        account=list[0]

        global Tm,Tm_d

        shutil.copyfile("stylelist.data","stylelist2.data")
        Tm=time.strftime('%Y-%m-%d %H%M%S',time.localtime(time.time()))
        Tm_ymd=time.strftime('%Y-%m-%d',time.localtime(time.time()))
        Tm_d=Tm+'.data'
        os.rename("stylelist2.data",Tm_d)


        def mov_():   
            
            Add_total.add_total(account)
            total=Get_total.get_total(account)
            Tm_d2=str(total)+Tm_d
            os.rename(Tm_d,Tm_d2)
            
            if int(Tm_d2[-7])!=0:
                Tm_d3=Tm_d2[:-7]+str(int(Tm_d2[-7:-5])+1)+account+'.data'
            else:
                Tm_d3=Tm_d2[:-6]+str(int(Tm_d2[-6])+1)+account+'.data'
            
            filename=list[0]
            if os.path.exists(filename):
                shutil.copyfile(Tm_d2,Tm_d3)
                shutil.move(Tm_d2,filename)
                shutil.move(Tm_d3,Tm_ymd)
            else:
                os.mkdir(filename)
                shutil.move(Tm_d2,filename)

        def cal_(list):
            stylelistfile=Tm_d
            f = file(stylelistfile)
            stylelist = p.load(f)
            
            for i in range(1,len(list)):
                if list[i]!=0:
                    price=stylelist[i-1]
                    price[1]=list[i]
                
            f = file(stylelistfile, 'w')
            p.dump(stylelist, f) 
            f.close()
            
            sum=0
            for style,price in stylelist.items():
                zl=int(price[0])*int(price[1])
                sum+=zl
            
            return sum

        bala=Get_bala.get_bala(account)
        sum=cal_(list)
        last=bala-sum

        if sum!=0:
            if last>=0:   
                Sub_bala.sub_(account,sum)
                mov_()
                return 'Ordered successfully! Your balance still remain %s yuan' % last
            else:
                os.remove(Tm_d)
                return "Insufficient balance! You need to add some to your balance! "   
        else:
            os.remove(Tm_d)
            return 'There is no order! Please go back to order something! ' 
    

#历史点单记录查看后台

#修改密码功能后台
    
            
    

